//
//  AddCardInfoViewController.m
//  HuLaQuan
//
//  Created by hok on 1/20/16.
//  Copyright © 2016 Jianghao. All rights reserved.
//

#import "AddCardInfoViewController.h"

//cells
#import "YuTypeInfoCell.h"
#import "ConfirmButtonCell.h"

//labels
#import "YuUserCellLabel.h"

//Logic model
#import "GetUserDetailInfoEngine.h"
#import "AddCardCheckInfoEngine.h"

//
#import "AddCardUserInfoViewController.h"

//Back To
#import "BankCardListViewController.h"
#import "QRCodeViewController.h"
#import "GenericConvenientPayHomeController.h"

#define kUserNamePlaceholder @"输入本人姓名"

@interface AddCardInfoViewController ()<UITextFieldDelegate>

@property (nonatomic,strong) NSArray *items;

@property(nonatomic,strong)NSString *userName;
@property(nonatomic,strong)NSString *cardNumber;


//Logic Model
@property (nonatomic,strong) GetUserDetailInfoEngine *getUserInfoEngine;
@property (nonatomic,strong) AddCardCheckInfoEngine *addCardCheckInfoEngine;

@end


static NSString * const YuTypeInfoCellIdentifier = @"YuTypeInfoCell";
static NSString * const ConfirmButtonCellIdentifier = @"ConfirmButtonCell";

@implementation AddCardInfoViewController
- (GetUserDetailInfoEngine *)getUserInfoEngine
{
    if (!_getUserInfoEngine) {
        _getUserInfoEngine = [[GetUserDetailInfoEngine alloc] init];
    }
    return _getUserInfoEngine;
}
- (AddCardCheckInfoEngine *)addCardCheckInfoEngine
{
    if (!_addCardCheckInfoEngine) {
        _addCardCheckInfoEngine = [[AddCardCheckInfoEngine alloc] init];
    }
    return _addCardCheckInfoEngine;
}
- (NSArray *)items
{
    if (!_items) {
        _items = @[@"持卡人",@"卡号"];
    }
    return _items;
}

- (void)setupUI
{
    [self setupNavBackButton];
    
    [self setupFooterForTableView];
    
    [self.tableView registerNib:[YuTypeInfoCell nib] forCellReuseIdentifier:YuTypeInfoCellIdentifier];
    [self.tableView registerNib:[ConfirmButtonCell nib] forCellReuseIdentifier:ConfirmButtonCellIdentifier];
    
    self.title = @"绑定银行卡";
    
    [self setupTapGesture];
    
    
}
#pragma mark UITableViewDataSource

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    return indexPath.row ==2 ? kConfirmButtonCellHeight : kNormalCellHeight;
    
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 3;
    
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    
    return 40;
    
    
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section

{
    
    CGRect frameRect = CGRectMake(25, 0, 200, 40);
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 200, 40)];
    YuUserCellLabel *textSection = [[YuUserCellLabel alloc] initWithFrame:frameRect];
    textSection.text = @"请绑定持卡人信息";
    [view addSubview:textSection];
    return view;
    
    
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    if (indexPath.row < 2) {
        YuTypeInfoCell *cell = [tableView dequeueReusableCellWithIdentifier:YuTypeInfoCellIdentifier
                                                               forIndexPath:indexPath];
        if(indexPath.row == 0)
        {
            cell.textField.placeholder = kUserNamePlaceholder;
            if (self.userName.length) {
                cell.textField.text = self.userName;
            }
        }
        else
        {
            cell.textField.placeholder = kCardNumberPlaceholder;
        }
        [cell.textField addTarget:self action:@selector(detaileAddressFieldWithText:) forControlEvents:UIControlEventEditingChanged];
         cell.textField.tag = indexPath.row;
        cell.textField.delegate = self;
        cell.titleLabel.text = self.items[indexPath.row];
        return cell;
        
    }else{
        ConfirmButtonCell *cell = [tableView dequeueReusableCellWithIdentifier:ConfirmButtonCellIdentifier
                                                                  forIndexPath:indexPath];
        
        [cell.confirmButton setTitle:@"下一步" forState:UIControlStateNormal];
        
        cell.banksButton.hidden = NO;
        
        [cell.banksButton addTarget:self action:@selector(tapBanksButton) forControlEvents:UIControlEventTouchUpInside];
        cell.confirm = (ClickBlock)^(){
            [self tapNextButton];
        };
        
        if (self.userName.length && self.cardNumber.length) {
            cell.confirmButton.enabled = YES;
        }else{
            cell.confirmButton.enabled = NO;
        }
        
        return cell;
    }
    
    
    
    
}
//getInformation
- (void)detaileAddressFieldWithText:(UITextField *)textField
{
    switch (textField.tag) {
        case 0:
            self.userName = textField.text;
            break;
        default:
            self.cardNumber = textField.text;
            break;
    }
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
}


#pragma mark - Textfield delegate
- (void)textFieldDidBeginEditing:(UITextField *)textField{
    
    textField.placeholder = @"";
    
}

- (void)textFieldDidEndEditing:(UITextField *)textField{
    
    if (textField.tag == 0) {
        if (textField.text.length == 0 ) {
            textField.placeholder = kUserNamePlaceholder;
            
        }
        
    }else{
        if (textField.text.length == 0 ) {
            textField.placeholder = kCardNumberPlaceholder;
            
        }
    }
    if (self.userName.length == 0 || self.cardNumber.length ==0) {
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:2 inSection:0];
        ConfirmButtonCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
        cell.confirmButton.enabled = NO;
    }
    
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    return YES;
}
- (BOOL)textField:(UITextField*)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    
    if (self.userName.length > 0 && self.cardNumber.length > 0) {
        
        
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:2 inSection:0];
        ConfirmButtonCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
        cell.confirmButton.enabled = YES;
    }
    return YES;
    
    // return [self validateNumber:string];
}

#pragma mark - Button Events
- (void)tapBanksButton
{
    [self performSegueWithIdentifier:@"ShowValidBankListFromAddCardInfo" sender:self];
}
- (void)tapNextButton
{
    if (self.userName.length && self.cardNumber.length) {
        [YuNetworkStatusUtilities showProgressMessage:NETWORK_LOADING];
        [self.addCardCheckInfoEngine getCardInfo:self.cardNumber name:self.userName];
    }
    
}

#pragma mark - Call Back
- (void)getUserInfoFinish:(NSNotification*) notification
{
    
    [YuNetworkStatusUtilities dismissHUD];
    
    NSDictionary *messageDic = [notification object];//获取到传递的对象
    if ([messageDic[@"isSuccess"] boolValue]) {
        
        if (messageDic[@"result"] && ![messageDic[@"result"][@"realName"] isEqualToString:@"Anonymous"]) {
            self.userName = messageDic[@"result"][@"realName"];
            [self.tableView reloadData];
            
        }
        
    }else{
        [self showNetWorkError:messageDic[@"message"]];
        
    }
}

- (void)getCardInfoFinish:(NSNotification*) notification
{
    
    [YuNetworkStatusUtilities dismissHUD];
    
    NSDictionary *messageDic = [notification object];//获取到传递的对象
    if ([messageDic[@"isSuccess"] boolValue]) {
        [self performSegueWithIdentifier:@"ShowAddCardUserInfo" sender:self];
    }else{
        [self showNetWorkError:messageDic[@"message"]];
        
    }
}

#pragma mark - Life Cycle
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:YES];
    
    // [self.navigationController setNavigationBarHidden:YES animated:YES];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(getUserInfoFinish:) name:@"GetUserInfoFinish" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(getCardInfoFinish:) name:@"GetCardInfoFinish" object:nil];
    
    [YuNetworkStatusUtilities showProgressMessage:NETWORK_LOADING];
    [self.getUserInfoEngine getUserInfo];
    
}
- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:YES];
    
    
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"GetUserInfoFinish" object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"GetCardInfoFinish" object:nil];
    
}

#pragma mark - Navigation Back
- (void)goBackAction
{
    [[UIApplication sharedApplication].keyWindow endEditing:YES];
    UIAlertController *x = [UIAlertController alertWithTitle:@"提示" andMessage:@"是否放弃绑定银行卡操作" andBlock:^(UIAlertAction *action ) {
        if ([action.title isEqualToString:@"好的"]) {
            if ([self.navigationController.viewControllers[1] isKindOfClass:[BankCardListViewController class]])
            {
                [self.navigationController popToViewController:self.navigationController.viewControllers[1] animated:YES];
            }
            else if ([self.navigationController.viewControllers[1] isKindOfClass:[QRCodeViewController class]])
            {
                [self.navigationController popToViewController:self.navigationController.viewControllers[1] animated:YES];
            }else if([self.navigationController.viewControllers[1] isKindOfClass:[GenericConvenientPayHomeController class]])
            {
                [self.navigationController popToViewController:self.navigationController.viewControllers[1] animated:YES];
            }else{
                [self.navigationController popViewControllerAnimated:YES];
            }
        }
        
    }  type:@"confirmAndCancel"];
    [self presentViewController:x animated:YES completion:nil];
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
    if([segue.identifier isEqualToString:@"ShowAddCardUserInfo"])
    {
        AddCardUserInfoViewController *controller = (AddCardUserInfoViewController *) [segue destinationViewController];
        controller.addCardCheckInfoEngine = self.addCardCheckInfoEngine;
    }
}


@end
